import { SchemaManage } from '@/components/SchemaComponent';
import { useEffect, useMemo, useRef, useState } from 'react';
import { connect, history } from 'umi';
import { MyCheckManageService, getMcontractByIDService, handlCheckManageService } from '../services';
import { ManageCommonAPI } from '@/pages/type';
import { ManageTabSwitch, getTableColumns } from '../mconfig';
import { WorkCurrentNodesImg } from '@/components/WorkflowCommon';
import { getKeyRouter } from '@/utils';
import { message } from 'antd';
import { usePageRouterPayload } from '@/layouts/UserLayout/MyHooks';

const ContractCheckManage: React.FC<ContractCheckManageAPI.IManageType> = ({ curRes, locationProps }) => {
  const schemaManageRef: any = useRef();

  /* 保存当前页面是否是待办任务,用于区分管理页功能 */
  const [tabSwitchType, setTabSwitchType] = useState<string | any>('NeedToDoTasks');

  /** 获取管理页数据【禁用】 */
  // const { data, loading, pagination, searchList, switchList, getTaskCheckData } = handlCheckManageService(curRes, tabSwitchType);

  /** 获取管理页数据【启用】 */
  const { getCheckManageRun, homePageLoading, pagination, data, switchList, searchList } = MyCheckManageService(curRes, tabSwitchType);

  /**  是否展开当前流程节点弹框 */
  const [openOtherFuncModal, setOpenOtherFuncModal] = useState<Record<string, any>>({
    openNodeImage: false,
    selectRows: {},
    openAddSignModal: false,
  });

  /** 保存变更合同ID */
  const [modifyInfoDetail, setModifyInfoDetail] = useState<Record<string, any>>({});

  useEffect(() => {
    if (locationProps?.state?.tabsPaneKey) {
      /** 获取权限参数 */
      const queryParams: ManageCommonAPI.ISwitchList = ManageTabSwitch(curRes);
      let manageTabsKey: string = tabSwitchType;
      let queryPayload: Record<string, any> | any = {};
      if (locationProps?.state?.tabsPaneKey == '1') {
        manageTabsKey = 'NeedToDoTasks';
      } else if (locationProps?.state?.tabsPaneKey == '4') {
        manageTabsKey = 'CompletedTasks';
      }
      queryPayload = queryParams?.find((item: any) => item?.key == manageTabsKey)?.params;

      // 处理选中
      schemaManageRef?.current?.setSwitch({
        key: manageTabsKey,
        params: queryPayload,
      });

      onSwitch(manageTabsKey, {}, queryPayload);
    }
  }, [locationProps?.state]);

  /** 切换方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    if (key) {
      setTabSwitchType(key);
      getCheckManageRun({ ...params, ...searchValues });
    }
  };

  /** 重置 */
  const onReset = (values: any) => {
    getCheckManageRun({ ...values });
  };

  /** 搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    getCheckManageRun({ ...request });
  };

  /**  分页change 方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getCheckManageRun({ pageSize, current, ...params });
  };

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      history.push({
        pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: modifyInfoDetail?.id,
          pageInfo: {
            pID: modifyInfoDetail?.pID ? modifyInfoDetail?.pID : null,
            id: modifyInfoDetail?.id ? modifyInfoDetail?.id : null,
          },
          pIDDetailInfo: { ...res?.obj },
        },
      });
      setModifyInfoDetail({});
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDRun } = getMcontractByIDService(detailsCallback);

  /** OA测试回调 */
  const oaDetailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      history.push({
        pathname: `/contractController/taskDataGrid/{paramValue}/{params}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: modifyInfoDetail?.id,
          pageInfo: {
            pID: modifyInfoDetail?.pID ? modifyInfoDetail?.pID : null,
            id: modifyInfoDetail?.id ? modifyInfoDetail?.id : null,
          },
          pIDDetailInfo: { ...res?.obj },
        },
      });
      setModifyInfoDetail({});
    } else {
      message.error(res?.msg);
    }
  };

  /** OA测试 */
  const oaTest = getMcontractByIDService(oaDetailCallback);

  /** 表格操作按钮点击方法 */
  const onOptClick: ContractCheckManageAPI.IOperationClick = {
    onView: (resObj) => {
      /** 结构pcUrl中的state参数 */
      let slicePcUrl = usePageRouterPayload(resObj?.pcUrl?.split('state=')[1]);
      let pID = slicePcUrl?.pBusinessID;
      let id = slicePcUrl?.businessID;

      if (slicePcUrl?.changeWayStr === '0' || slicePcUrl?.changeWayStr === '1') {
        setModifyInfoDetail({ pID, id });
        if (pID) {
          getMcontractByIDRun({ id: pID });
        }
      } else if (slicePcUrl?.changeWayStr === 'null') {
        history.push({
          pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'detail',
            id: id,
            pageInfo: {
              pID: pID || null,
              id: id || null,
            },
            pIDDetailInfo: {
              id: id || null,
              pID: pID || null,
              contractCode: null,
            },
          },
        });
      }
    },
    onStep: (resObj) => {
      setOpenOtherFuncModal({
        openNodeImage: true,
        selectRows: resObj,
        openAddSignModal: false,
      });
    },
    onHand: (resObj) => {
      /** 结构pcUrl中的state参数 */
      let slicePcUrl = usePageRouterPayload(resObj?.pcUrl?.split('state=')[1]);
      let pID = slicePcUrl?.pBusinessID;
      let id = slicePcUrl?.businessID;

      if (slicePcUrl?.changeWayStr === '0' || slicePcUrl?.changeWayStr === '1') {
        setModifyInfoDetail({ pID, id });
        if (pID) {
          getMcontractByIDRun({ id: pID });
        }
      } else if (slicePcUrl?.changeWayStr === 'null') {
        history.push({
          pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'detail',
            id: id,
            pID: pID,
          },
        });
      }
    },

    onOA: (resObj) => {
      /** 结构pcUrl中的state参数 */
      let slicePcUrl = usePageRouterPayload(resObj?.pcUrl?.split('state=')[1]);
      let pID = slicePcUrl?.pBusinessID;
      let id = slicePcUrl?.businessID;

      if (slicePcUrl?.changeWayStr === '0' || slicePcUrl?.changeWayStr === '1') {
        setModifyInfoDetail({ pID, id });
        // if (pID) { getMcontractByIDRun({ id: pID }) }
        if (pID) {
          oaTest?.getMcontractByIDRun({
            id: pID,
          });
        }
      } else if (slicePcUrl?.changeWayStr === 'null') {
        history.push({
          pathname: `/contractController/taskDataGrid/{paramValue}/{params}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'detail',
            id: id,
            taskId: id,
            pageInfo: {
              pID: pID || null,
              id: id || null,
            },
            pIDDetailInfo: {
              // ...resObj?.attributes,
              id: id || null,
              pID: pID || null,
              contractCode: null,
              // contractCode: resObj?.attributes?.busi_contractCode,
            },
          },
        });
      }
    },
  };

  /** 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, onOptClick, tabSwitchType);
  }, [curRes, tabSwitchType, data?.rows?.length]);

  return (
    <>
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList, //头部切换列表
          searchList, //搜索表单列表
          onReset, //重置
          onSwitch, //头部切换
          onSearch, //搜索方法
        }}
        actionList={[]} //Table头部操作按钮列表
        tableProps={{
          // table 表格属性
          columns,
          dataSource: data?.rows,
          loading: homePageLoading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange: onPageChange, //分页change方法
        }}
      />

      {/* 当前流程节点 */}
      {openOtherFuncModal?.openNodeImage && (
        <WorkCurrentNodesImg
          onClose={() => {
            setOpenOtherFuncModal({
              ...openOtherFuncModal,
              openNodeImage: false,
            });
          }}
          openVisible={openOtherFuncModal?.openNodeImage}
          requestController="contractController"
          procInstID={openOtherFuncModal?.selectRows?.procInstID}
        />
      )}
    </>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractCheckManage);

/** onView **/
// if (resObj?.attributes.busi_changeWay == 0 || resObj?.attributes.busi_changeWay == 1) {
//   setModifyInfoDetail(resObj?.attributes);
//   getMcontractByIDRun({
//     id: resObj?.attributes.busi_pID,
//   });
// } else {
//   history.push({
//     pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
//     state: {
//       pageType: 'detail',
//       id: resObj?.attributes.busi_id,
//       pageInfo: {
//         pID: resObj?.attributes?.busi_pID ? resObj?.attributes?.busi_pID : null,
//         id: resObj?.attributes?.busi_id ? resObj?.attributes?.busi_id : null,
//       },
//       pIDDetailInfo: {
//         ...resObj?.attributes,
//         id: resObj?.attributes?.busi_id ? resObj?.attributes?.busi_id : null,
//         pID: resObj?.attributes?.busi_pID ? resObj?.attributes?.busi_pID : null,
//         contractCode: resObj?.attributes?.busi_contractCode,
//       },
//     },
//   });
// }

/** oaDetailCallback **/
// id: modifyInfoDetail?.attributes?.clickType ? modifyInfoDetail?.attributes?.pID : modifyInfoDetail?.attributes?.busi_id,
// pageInfo: {
//   pID: modifyInfoDetail?.attributes?.busi_pID ? modifyInfoDetail?.attributes?.busi_pID : null,
//   id: modifyInfoDetail?.attributes?.busi_id ? modifyInfoDetail?.attributes?.busi_id : null,
//   procInstID: modifyInfoDetail?.procInstID,
// },
// pIDDetailInfo: {
//   ...res?.obj,
// },

/** onOA **/
// if (resObj?.attributes?.busi_changeWay == 0 || resObj?.attributes?.busi_changeWay == 1) {
//   setModifyInfoDetail(resObj);
//   oaTest?.getMcontractByIDRun({
//     id: resObj?.attributes.busi_pID,
//   });
// } else {
//   history.push({
//     pathname: `/contractController/taskDataGrid/{paramValue}/{params}/:${getKeyRouter()}${getKeyRouter()}`,
//     state: {
//       pageType: 'detail',
//       id: resObj?.attributes.busi_id,
//       pageInfo: {
//         pID: resObj?.attributes?.busi_pID ? resObj?.attributes?.busi_pID : null,
//         id: resObj?.attributes?.busi_id ? resObj?.attributes?.busi_id : null,
//         procInstID: resObj?.procInstID,
//       },
//       pIDDetailInfo: {
//         ...resObj?.attributes,
//         id: resObj?.attributes?.busi_id ? resObj?.attributes?.busi_id : null,
//         pID: resObj?.attributes?.busi_pID ? resObj?.attributes?.busi_pID : null,
//         contractCode: resObj?.attributes?.busi_contractCode,
//       },
//     },
//   });
// }

/** onHand **/
// // if (resObj?.attributes.busi_changeWay == 0 || resObj?.attributes.busi_changeWay == 1) {
// //   setModifyInfoDetail(resObj);
// //   getMcontractByIDRun({
// //     id: resObj?.attributes.busi_pID,
// //   });
// // } else {
// //   history.push({
// //     pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
// //     state: {
// //       pageType: 'detail',
// //       id: resObj?.orderID,
// //       pID: resObj?.attributes.busi_pID,
// //     },
// //   });
// // }

// if (resObj?.attributes.busi_changeWay == 0 || resObj?.attributes.busi_changeWay == 1) {
//   setModifyInfoDetail(resObj?.attributes);
//   oaTest?.getMcontractByIDRun({
//     id: resObj?.attributes.busi_pID,
//   });
// } else {
//   history.push({
//     pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
//     state: {
//       pageType: 'detail',
//       id: resObj?.attributes?.busi_id,
//       pageInfo: {
//         pID: resObj?.attributes?.busi_pID ? resObj?.attributes?.busi_pID : null,
//         id: resObj?.attributes?.busi_id ? resObj?.attributes?.busi_id : null,
//       },
//       pIDDetailInfo: {
//         ...resObj?.attributes,
//       },
//     },
//   });
// }
